package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.ErrorReportDao;
import jumpingnotes.model.entity.ErrorReport;
import net.jf.lucene.analysis.mmseg.MMSegAnalyzer;

import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;

public class ErrorReportHibernateDao extends GenericHibernateDao<ErrorReport> implements ErrorReportDao
{
	public ErrorReportHibernateDao()
	{
		super(ErrorReport.class);
	}

	@SuppressWarnings("unchecked")
	public void indexErrorReport()
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		List<ErrorReport> errorreportList = session.createCriteria(ErrorReport.class).list();
		for (ErrorReport errorreport : errorreportList)
		{
			fullTextSession.index(errorreport);
		}
	}

	@SuppressWarnings("unchecked")
	public List<ErrorReport> searchErrorReport(String keyword, int firstResult, int maxResults)
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		try
		{
			MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[] { "subject", "body" },
					new MMSegAnalyzer());
			org.apache.lucene.search.Query query = parser.parse(keyword);
			Query hibQuery = fullTextSession.createFullTextQuery(query, ErrorReport.class);

			if (firstResult >= 0)
				hibQuery.setFirstResult(firstResult);
			if (maxResults > 0)
				hibQuery.setMaxResults(maxResults);

			List<ErrorReport> result = hibQuery.list();
			return result;
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
